//
//  TSWebViewController.m
//  Pods-TSWebKit_Example
//
//  Created by Zac on 2020/10/27.
//

#import "TSWebViewController.h"
#import "Masonry.h"

#define kScreen_Height [UIScreen mainScreen].bounds.size.height
#define kScreen_Width  [UIScreen mainScreen].bounds.size.width
#define kStatusBar_Height [[UIApplication sharedApplication] statusBarFrame].size.height

#define TSWebStatusBarHeight  (UIScreen.mainScreen.bounds.size.height >= 812?40:20)
#define TSWebNavibarHeight  (UIScreen.mainScreen.bounds.size.height >= 812?84:64)
#define TSWebBottombarHeight  (UIScreen.mainScreen.bounds.size.height >= 812?34:0)

NSString * const TSWebViewKeyTitle = @"title";
NSString * const TSWebViewKeyEstimateProgress = @"estimatedProgress";

@interface TSWebViewController ()

@property (nonatomic, strong) NSURL *URL;
@property (nonatomic, strong) NSDictionary *header;

@end

@implementation TSWebViewController {
    NSURLConnection *connection;
}

- (instancetype)initWithURL:(NSURL *)URL {
    return [self initWithURL:URL header:nil];
}

- (instancetype)initWithURL:(NSString *)URL header:(NSDictionary *)header {
    if (self = [super init]) {
        self.URL = [NSURL URLWithString:URL];
        self.header = header;
        if ([URL hasPrefix:@"http"] || [URL hasPrefix:@"https"]) {
            if ([URL rangeOfString:@"?"].location != NSNotFound) {
                self.URL = [NSURL URLWithString:[NSString stringWithFormat:@"%@&t=%@", URL, [self getNowTimestamp]]];
            } else {
                self.URL = [NSURL URLWithString:[NSString stringWithFormat:@"%@?t=%@", URL, [self getNowTimestamp]]];
            }
        }
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.edgesForExtendedLayout = UIRectEdgeNone;
    [self _setup];
    [self _loadURL];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.view.backgroundColor = UIColor.whiteColor;
    [self.navigationController setNavigationBarHidden:NO];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
    [self registerCameraJsBridge];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.webView removeJavascriptObject:nil];
}

- (void)_setup {
    [self.webView addSubview:self.progressView];
    [self.webView addObserver:self
                   forKeyPath:TSWebViewKeyEstimateProgress
                      options:NSKeyValueObservingOptionNew context:nil];
    [self.webView addObserver:self
                   forKeyPath:TSWebViewKeyTitle
                      options:NSKeyValueObservingOptionNew
                      context:nil];
}

- (void)registerCameraJsBridge {
    [self.webView addJavascriptObject:[[TSBridgeManager alloc] initWithHandle:self] namespace:nil];
}

- (void)observeValueForKeyPath:(NSString *)keyPath
                      ofObject:(id)object
                        change:(NSDictionary<NSKeyValueChangeKey,id> *)change
                       context:(void *)context {
    if (object == self.webView &&
        [keyPath isEqualToString:TSWebViewKeyEstimateProgress]) {
        CGFloat newprogress = [[change objectForKey:NSKeyValueChangeNewKey] doubleValue];
        [self.progressView setProgress:newprogress animated:YES];
        if (newprogress >= 1) {
            [UIView animateWithDuration:0.25f
                                  delay:0.3f
                                options:UIViewAnimationOptionCurveEaseOut animations:^{
            } completion:^(BOOL finished) {
                self.progressView.hidden = YES;
            }];
        }
    } else if ([object isEqual:self.webView] &&
               [keyPath isEqualToString:TSWebViewKeyTitle]) {
           self.title = self.webView.title;
    }
    else {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

#pragma mark - NSURLConnection
- (void)connection:(NSURLConnection *)connection
  didFailWithError:(NSError *)error {
    [self.progressView setProgress:0 animated:NO];
}

#pragma mark -- load request
- (void)_loadURL {
    NSMutableURLRequest *request = nil;
    if ([self.URL.absoluteString hasPrefix:@"http"] || [self.URL.absoluteString hasPrefix:@"https"])
    {
        request = [NSMutableURLRequest requestWithURL:self.URL
                                          cachePolicy:NSURLRequestUseProtocolCachePolicy
                                      timeoutInterval:15.0];
        for (NSString *key in self.header.allKeys) {
            NSString *value = self.header[key];
            [request setValue:value forHTTPHeaderField:key];
        }
    } else {
        NSURL *fileURL = [NSURL fileURLWithPath:self.URL.absoluteString];
        request = [NSMutableURLRequest requestWithURL:fileURL];
    }
    [self.webView loadRequest:request];
}

- (NSString *)getNowTimestamp {
    NSDate *date = [NSDate date]; // 获得时间对象
    NSTimeZone *zone = [NSTimeZone systemTimeZone]; // 获得系统的时区
    NSTimeInterval time = [zone secondsFromGMTForDate:date];//以秒为单位返回当前时间与系统格林尼治时间的差
    NSDate *dateNow = [date dateByAddingTimeInterval:time];// 然后把差的时间加上,就是当前系统准确的时间
    long long localTimestamp = (long long)([dateNow timeIntervalSince1970] * 1000);
    return @(localTimestamp).stringValue;
}

#pragma mark - get & set
- (TSWebView *)webView {
    if (!_webView) {
        _webView = [[TSWebView alloc] init];
        [self.view addSubview:_webView];
        [_webView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.top.equalTo(self.view);
            make.bottom.equalTo(self.view.mas_bottom).offset(-TSWebBottombarHeight);
        }];
    }
    return _webView;
}

- (UIProgressView *)progressView {
    if (!_progressView) {
        _progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.frame), 2)];
        [_progressView setTintColor:[UIColor colorWithRed:31.0/255.0 green:66.0/255.0 blue:123.0/255.0 alpha:1.0]];
        _progressView.progress = 0.4;
        _progressView.backgroundColor = [UIColor whiteColor];
    }
    return _progressView;
}

- (void)dealloc {
    [self.webView removeObserver:self forKeyPath:TSWebViewKeyTitle];
    [self.webView removeObserver:self forKeyPath:TSWebViewKeyEstimateProgress];
}

@end
